<template>
  <el-drawer
    :append-to-body="true"
    title="条件设置"
    v-model="visible"
    class="condition_copyer"
    :show-close="false"
    :size="550"
    :before-close="saveCondition"
  >
    <template #header="{ titleId, titleClass }">
      <h3 :id="titleId" :class="titleClass">条件设置</h3>
      <select
        v-model="conditionConfig.priorityLevel"
        class="priority_level"
        v-if="conditionsConfig.conditionNodes.length"
      >
        <option
          v-for="item in conditionsConfig.conditionNodes.length"
          :value="item"
          :key="item"
        >
          优先级{{ item }}
        </option>
      </select>
    </template>
    <div class="demo-drawer__content">
      <div class="condition_content drawer_content">
        <span class="tip">满足以下条件时进入当前分支</span>
        <div v-for="(u, i) in conditionGroupList" :key="i">
          <div class="or_meet" v-if="i > 0">或满足</div>
          <div class="condition_group">
            <div class="condition_group_title">
              <!-- <span class="title">条件组{{ i + 1 }}</span> -->
              <span class="title">条件组</span>
              <el-icon
                class="el-icon-delete"
                @click="delConditionGroup(i)"
                v-if="conditionGroupList.length > 1"
                ><Delete
              /></el-icon>
            </div>
            <div
              class="condition_group_content"
              v-for="(u2, i2) in u"
              :key="i2"
            >
              <div class="danger">
                <span v-if="i2 == 0">
                  当 &nbsp;
                  <span style="color: red; font-weight: bold"
                    >建议将字段设置为必填后，使用必填字段作为设置条件</span
                  >
                </span>
                <span v-else>且</span>
                <el-icon
                  class="el-icon-delete"
                  @click="delCondition(i, i2)"
                  v-if="u.length > 1"
                >
                  <Delete />
                </el-icon>
              </div>
              <el-select
                v-model="u2.formType"
                placeholder="请选择"
                @change="changeFormType(i, i2)"
                class="mt_10"
              >
                <el-option
                  v-for="(item, index) in formFiledList1"
                  :key="item.fieldId"
                  :label="`${item.fieldName}${index != 0 ? (item.is_required ? '（必填）' : '（非必填）') : ''}`"
                  :value="item.fieldId"
                />
              </el-select>
              <el-select
                v-model="u2.conditionType"
                placeholder="请选择"
                class="mt_10"
              >
                <el-option
                  v-for="item in u2.conditionTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- 选项 -->
              <el-select
                v-if="u2.showType == 1"
                v-model="u2.value"
                placeholder="请选择"
                :class="['mt_10', !flag && !u2.value ? 'flag-false' : '']"
              >
                <el-option
                  v-for="item in u2.optionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <!-- 发起人 -->
              <div
                v-else-if="u2.showType == 2"
                :class="[
                  'user_box mt_10',
                  !flag && !u2.value.length ? 'flag-false' : '',
                ]"
              >
                <div class="user_box_content">
                  <span class="placeholder" v-if="!u2.value.length">
                    请选择人员/职务/部门
                  </span>
                  <el-tag
                    v-for="(u3, i3) in u2.value"
                    :key="i3"
                    closable
                    @close="delUser(i, i2, i3)"
                    >{{ u3.name }}</el-tag
                  >
                </div>
                <div>
                  <span class="placeholder">添加</span>
                  <span class="add_user" @click="addPromoter(i, i2)">人员</span>
                  <span class="add_user" @click="addDept(1, i, i2)">职务</span>
                  <span class="add_user" @click="addDept(2, i, i2)">部门</span>
                </div>
              </div>
              <!-- 单选 -->
              <el-radio-group v-else-if="u2.showType == 2.1" v-model="u2.value">
                <el-radio
                  v-for="item in u2.optionList"
                  :key="item.value"
                  :value="item.value"
                >
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group
                v-else-if="u2.showType == 2.2"
                v-model="u2.value"
              >
                <el-checkbox
                  v-for="item in u2.optionList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-checkbox-group>
              <!-- 时间 -->
              <el-time-picker
                v-else-if="u2.showType == 6"
                v-model="u2.value"
                value-format="HH:mm:ss"
                placeholder="选择时间"
                :class="['mt_10', !flag && !u2.value ? 'flag-false' : '']"
              />
              <!-- 日期框 -->
              <el-date-picker
                v-else-if="
                  u2.showType == 4 ||
                  u2.showType == 4.1 ||
                  u2.showType == 4.2 ||
                  u2.showType == 4.3
                "
                v-model="u2.value"
                :type="
                  u2.showType == 4
                    ? 'date'
                    : u2.showType == 4.1
                      ? 'datetime'
                      : u2.showType == 4.2
                        ? 'year'
                        : 'month'
                "
                :format="
                  u2.showType == 4
                    ? 'YYYY-MM-DD'
                    : u2.showType == 4.1
                      ? 'YYYY-MM-DD HH:mm:ss'
                      : u2.showType == 4.2
                        ? 'YYYY'
                        : 'YYYY-MM'
                "
                :value-format="
                  u2.showType == 4
                    ? 'YYYY-MM-DD'
                    : u2.showType == 4.1
                      ? 'YYYY-MM-DD HH:mm:ss'
                      : u2.showType == 4.2
                        ? 'YYYY'
                        : 'YYYY-MM'
                "
                placeholder="选择日期"
                :class="['mt_10', !flag && !u2.value ? 'flag-false' : '']"
              />
              <!-- 输入框 -->
              <el-input
                v-model="u2.value"
                type="text"
                placeholder="请输入"
                :class="['mt_10', !flag && !u2.value ? 'flag-false' : '']"
                :style="u2.showType == 5 ? 'display:none' : ''"
                v-else
              />
            </div>
            <div class="add_btn" v-if="false">
              <el-button type="primary" link @click="addCondition(i)">
                <el-icon><Plus /></el-icon>
                &nbsp;添加条件
              </el-button>
            </div>
          </div>
        </div>
        <div class="add_group_btn" v-if="false">
          <el-button @click="addConditionGroup">
            <el-icon><Plus /></el-icon>
            &nbsp;添加条件组
          </el-button>
        </div>
      </div>
      <div class="demo-drawer__footer clear">
        <el-button type="primary" @click="saveCondition">确 定</el-button>
        <el-button @click="closeDrawer">取 消</el-button>
      </div>
    </div>
    <!-- 按人员选取 -->
    <FlowDialogTeacherSelection
      :importVisible="promoterVisible"
      :checkedList="checkedPromoterList"
      @closeDialog="surePromoter"
    />
    <!-- 按部门职务选取 -->
    <FlowDialogDeptDutiesSelection
      :importVisible="deptDutiesVisible"
      :checkedList="checkedDeptDutiesList"
      :type="type"
      @closeDialog="sureDeptDuties"
    />
  </el-drawer>
</template>
<script setup>
import { Delete, Plus } from "@element-plus/icons-vue";
import $func from "@/utils/flow";
import { useFlowStore } from "@/stores/flow";

let conditionsConfig = ref({
  conditionNodes: [],
});
let conditionConfig = ref({});
let PriorityLevel = ref("");

let store = useFlowStore();
let { setCondition, setConditionsConfig } = store;
let tableId = computed(() => store.tableId);
let conditionsConfig1 = computed(() => store.conditionsConfig1);
let conditionDrawer = computed(() => store.conditionDrawer);
let formFiledList = computed(() => store.formFiledListDiff);
let visible = computed({
  get() {
    return conditionDrawer.value;
  },
  set() {
    closeDrawer();
  },
});
watch(conditionsConfig1, (val) => {
  if (conditionDrawer.value) {
    conditionsConfig.value = val.value;
    PriorityLevel.value = val.priorityLevel;
    conditionConfig.value = val.priorityLevel
      ? conditionsConfig.value.conditionNodes[val.priorityLevel - 1]
      : { conditionList: [] };

    state.formFiledList1 = [
      {
        fieldId: 1,
        fieldName: "发起人",
        option: [],
        relation: [
          { value: 1, label: "属于" },
          { value: 2, label: "不属于" },
        ],
      },
    ];
    state.formFiledList1.push(...formFiledList.value);

    state.flag = true;
    if (conditionConfig.value.conditionList.length) {
      const list = JSON.parse(
        JSON.stringify(conditionConfig.value.conditionList),
      );
      list.forEach((item) => {
        item.forEach((item1) => {
          if (item1.formName == "radio") {
            item1.showType = 2.1;
          } else if (item1.formName == "checkbox") {
            item1.showType = 2.2;
            if (!Array.isArray(item1.value)) {
              if (item1.value) {
                item1.value = [item1.value];
              } else {
                item1.value = [];
              }
            }
          }
        });
      });
      state.conditionGroupList = list;
    } else {
      state.conditionGroupList = [
        [
          {
            formType: 1, //表单字段类型
            formName: "发起人",
            conditionType: 1, // 中间条件类型
            conditionTypeList: [
              { value: 1, label: "属于" },
              { value: 2, label: "不属于" },
            ],
            showType: 2, //选项显示类型 1下拉框 2点击后弹框 3输入框
            value: [], //选项值
            optionList: [],
          },
        ],
      ];
    }
  }
});

let state = reactive({
  formFiledList1: [], // 表单字段列表
  conditionGroupList: [],
  flag: true,
  // 人员部门职务选取
  promoterVisible: false,
  deptDutiesVisible: false,
  checkedPromoterList: [],
  checkedDeptDutiesList: [],
  type: 1,
  indexInfo: {
    index: 0,
    index2: 0,
  },
});
let {
  formFiledList1,
  conditionGroupList,
  promoterVisible,
  deptDutiesVisible,
  checkedPromoterList,
  checkedDeptDutiesList,
  type,
  flag,
  riqiType,
} = toRefs(state);

/**
 * 添加条件
 */
function addCondition(index) {
  const len = state.conditionGroupList[index].length;
  const i = len % state.formFiledList1.length;
  const obj = {
    formType: state.formFiledList1[i].fieldId,
    formName: state.formFiledList1[i].fieldName,
    conditionType: 1,
    conditionTypeList: state.formFiledList1[i].relation,
    showType: "",
    value: "",
    optionList: state.formFiledList1[i].option,
  };
  state.conditionGroupList[index].push(obj);
  changeFormType(index, len);
}
/**
 * 添加条件组
 */
function addConditionGroup() {
  const obj = {
    formType: state.formFiledList1[0].fieldId,
    formName: state.formFiledList1[0].fieldName,
    conditionType: 1,
    conditionTypeList: state.formFiledList1[0].relation,
    showType: "",
    value: "",
    optionList: state.formFiledList1[0].option,
  };
  state.conditionGroupList.push([obj]);
  changeFormType(state.conditionGroupList.length - 1, 0);
}
/**
 * 删除条件
 */
function delCondition(index, index2) {
  state.conditionGroupList[index].splice(index2, 1);
}

/**
 * 删除条件组
 */
function delConditionGroup(index) {
  state.conditionGroupList.splice(index, 1);
}
/**
 * 条件类型改变
 */
function changeFormType(index, index2) {
  let formType = state.conditionGroupList[index][index2].formType;
  let nowObj = state.formFiledList1.find((item) => item.fieldId === formType);
  state.conditionGroupList[index][index2].formName = nowObj.fieldName;
  // 获取选项列表
  const formInfo = state.formFiledList1.find((obj) => obj.fieldId == formType);
  state.conditionGroupList[index][index2].optionList = formInfo.option;
  state.conditionGroupList[index][index2].conditionTypeList = formInfo.relation;
  state.conditionGroupList[index][index2].conditionType = undefined;

  let showType = 0;
  if (formType == 1) {
    showType = 2; //发起人
  } else if (formInfo.type == 1) {
    showType = 3; //输入框
  } else if (formInfo.type == 2) {
    showType = 1; //下拉框
  } else if (formInfo.type == 2.1) {
    showType = 2.1;
  } else if (formInfo.type == 2.2) {
    showType = 2.2;
  } else if (formInfo.type == 3) {
    showType = 4; // 日期
  } else if (formInfo.type == 3.1) {
    showType = 4.1; // 日期
  } else if (formInfo.type == 3.2) {
    showType = 4.2; // 日期
  } else if (formInfo.type == 3.3) {
    showType = 4.3; // 日期
  } else if (formInfo.type == 3.4) {
    showType = 6; // 时间
  } else {
    showType = 5; // 隐藏
  }
  state.conditionGroupList[index][index2].value =
    showType == 2.2 || showType == 2 ? [] : "";
  state.conditionGroupList[index][index2].showType = showType;
}
/**
 * 选取人员
 */
function addPromoter(index, index2) {
  state.indexInfo = { index, index2 };
  let value = state.conditionGroupList[index][index2].value;
  if (value.length) {
    state.checkedPromoterList = value.filter((item) => item.type === 1);
  } else {
    state.checkedPromoterList = [];
  }
  state.promoterVisible = true;
}
/**
 * 确认人员
 */
function surePromoter(data) {
  state.promoterVisible = false;
  if (!data) return; //点击关闭窗口
  let i = state.indexInfo.index;
  let i2 = state.indexInfo.index2;
  let result = data.filter(
    (item) =>
      !state.conditionGroupList[i][i2].value.find((obj) => obj.id === item.id),
  );
  if (result.length) {
    state.conditionGroupList[i][i2].value = [
      ...state.conditionGroupList[i][i2].value,
      ...result,
    ];
  }
}
/**
 * 选取部门职务
 */
function addDept(type, index, index2) {
  state.indexInfo = { index, index2 };
  state.type = type;
  let value = state.conditionGroupList[index][index2].value;
  if (value.length) {
    if (type == 1) {
      state.checkedDeptDutiesList = value.filter((item) => item.type === 2);
    } else {
      state.checkedDeptDutiesList = value.filter((item) => item.type === 3);
    }
  } else {
    state.checkedDeptDutiesList = [];
  }
  state.deptDutiesVisible = true;
}
/**
 * 确认部门职务
 */
function sureDeptDuties(data) {
  state.deptDutiesVisible = false;
  if (!data) return; //点击关闭窗口
  let i = state.indexInfo.index;
  let i2 = state.indexInfo.index2;
  let result = data.filter(
    (item) =>
      !state.conditionGroupList[i][i2].value.find((obj) => obj.id === item.id),
  );
  if (result.length) {
    state.conditionGroupList[i][i2].value = [
      ...state.conditionGroupList[i][i2].value,
      ...result,
    ];
  }
}
/**
 * 删除人员/职务/部门
 */
function delUser(index, index2, index3) {
  state.conditionGroupList[index][index2].value.splice(index3, 1);
}
/**
 * 保存条件前验证
 */
function saveConditionValidate() {
  let flag = true;
  state.conditionGroupList.forEach((item) => {
    item.forEach((item2) => {
      if (
        ((item2.value.length === 0 || !item2.value) && item2.showType != 5) ||
        !item2.conditionType
      ) {
        ElMessage.warning("请完善条件");
        flag = false;
      }
    });
  });
  return flag;
}
/**
 * 保存条件
 */
const saveCondition = () => {
  state.flag = saveConditionValidate();
  if (!state.flag) return; // 验证未通过
  const groupList = JSON.parse(JSON.stringify(state.conditionGroupList));
  conditionsConfig.value.conditionNodes[PriorityLevel.value - 1].conditionList =
    groupList;
  closeDrawer();
  var a = conditionsConfig.value.conditionNodes.splice(
    PriorityLevel.value - 1,
    1,
  ); //截取旧下标
  conditionsConfig.value.conditionNodes.splice(
    conditionConfig.value.priorityLevel - 1,
    0,
    a[0],
  ); //填充新下标
  conditionsConfig.value.conditionNodes.map((item, index) => {
    item.priorityLevel = index + 1;
  });
  for (var i = 0; i < conditionsConfig.value.conditionNodes.length; i++) {
    conditionsConfig.value.conditionNodes[i].error =
      $func.conditionStr(conditionsConfig.value, i) == "请设置条件" &&
      i != conditionsConfig.value.conditionNodes.length - 1;
  }
  setConditionsConfig({
    value: conditionsConfig.value,
    flag: true,
    id: conditionsConfig1.value.id,
  });
};
const closeDrawer = (val) => {
  setCondition(false);
};
</script>
<style lang="scss" scoped>
.condition_copyer {
  .priority_level {
    position: absolute;
    top: 11px;
    right: 30px;
    width: 100px;
    height: 32px;
    background: rgba(255, 255, 255, 1);
    border-radius: 4px;
    border: 1px solid rgba(217, 217, 217, 1);
    font-size: 12px;
  }

  .condition_content {
    padding: 20px 20px 0;
    height: calc(100vh - 100px);
    overflow: auto;
    .tip {
      display: inline-block;
      margin-bottom: 20px;
      font-size: 14px;
      color: #646a73;
    }
    .or_meet {
      margin-bottom: 10px;
      color: #646a73;
      font-size: 14px;
    }
  }
}
.condition_group {
  width: 100%;
  margin: 0 auto 10px;
  padding-bottom: 4px;
  border: 1px solid #e4e5e7;
  border-radius: 3px;
  font-size: 14px;
  .condition_group_title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 40px;
    margin-bottom: 10px;
    padding: 0 12px;
    background-color: #f4f6f8;
    .title {
      font-weight: 700;
    }
  }
  .condition_group_content {
    padding: 8px 12px;
    .danger {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: #9ca2a9;
    }
    :deep(.mt_10) {
      margin-top: 8px;
    }
    .user_box {
      display: flex;
      width: 100%;
      padding: 4px 12px;
      min-height: 32px;
      line-height: 24px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      box-sizing: border-box;
      .placeholder {
        color: #9ca2a9;
      }
      .user_box_content {
        width: calc(100% - 130px);
        .el-tag {
          margin-right: 6px;
        }
      }
      .add_user {
        margin-left: 6px;
        color: #3370ff;
        cursor: pointer;
      }
    }
  }
  .el-icon-delete {
    color: #9ca2a9;
    cursor: pointer;
  }
  .add_btn {
    margin-top: 2px;
    padding: 0 12px;
    height: 30px;
    .el-button {
      padding: 5px;
      &:hover {
        color: #409eff;
        background-color: #eaf0ff;
      }
    }
    .el-icon {
      vertical-align: middle;
    }
  }
}
.add_group_btn {
  margin-top: 16px;
  .el-button {
    width: 100%;
    &:hover {
      color: #606266;
      background-color: #f2f3f5;
      border-color: #dcdfe6;
    }
  }
}
.flag-false {
  border-color: #ff5b4c !important;
  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #ff5b4c inset;
  }
  :deep(.el-select__wrapper) {
    box-shadow: 0 0 0 1px #ff5b4c inset;
  }
}
</style>
